package com.mainworks.commons.utils;

import com.mainworks.commons.entity.BaseParams;
import com.mainworks.commons.exception.BizException;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.util.List;

/**
 * @Author: HuangMinJie
 * @CreateDate: 2021/10/31 15:37
 * @Description:
 * @Version: 1.0.0.0
 * @ModifiedBy:
 * @ModifiedDate:
 * @ModifiedDescription:
 */

@Component
public class ParamsValidator {

    /**
     *
     * @param result
     * @return
     */
    public  static boolean validate(BindingResult result)
    {

        int errorCount = result.getErrorCount();
        if (errorCount>0){
            List<FieldError> fieldErrors = result.getFieldErrors();
            StringBuilder errMsg = new StringBuilder();
            for (FieldError fieldError : fieldErrors) {
                errMsg.append(fieldError.getDefaultMessage()).append("，");
            }
            String str = errMsg.toString();
            throw new BizException(str.substring(0,str.length()-1));
        }
        return true;
    }



    public static void paramsNotNull(BaseParams form)
    {
        if(form == null){
            throw new BizException("请求参数不能为空");
        }
    }

}

